package com.tencent.wxcloudrun.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.tencent.wxcloudrun.dto.CosAuthResponse;
import com.tencent.wxcloudrun.dto.DownLoadLinkInfo;
import com.tencent.wxcloudrun.dto.UploadLinkInfo;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
@Service
public class TxCosService {

    final static String bucket = "7072-prod-6g2xjx03c54348b1-1338619723";
    final static String region = "ap-shanghai";
    public UploadLinkInfo uploadLinkInfo;
    public CosAuthResponse getCosAuthSignConfig() {
        String url = "http://api.weixin.qq.com/_/cos/getauth";
        // 发送 GET 请求并获取响应结果
        String response = HttpUtil.get(url);
        System.out.println(StrUtil.format("TxCosAuth请求结果：{}", response));

        if (JSONUtil.isTypeJSON(response)) {
            // 使用 Hutool 的 JSONUtil 将 JSON 字符串转换为 Java 对象
            return JSONUtil.toBean(response, CosAuthResponse.class);
        } else {
            System.out.println("获取的响应不是有效的 JSON 格式：" + response);
            return null;
        }
    }

//    /**
//     * <a herf=https://developers.weixin.qq.com/miniprogram/dev/wxcloudservice/wxcloudrun/src/guide/weixin/open.html></a>
//     * @param file
//     * @return
//     * @throws IOException
//     */
//    public String uploadFileToCos(MultipartFile file) throws IOException {
//
//        String cloudPath = "your-cloud-path/" + file.getOriginalFilename();
//        // 使用 try-with-resources 语句确保 HttpResponse 资源被正确关闭
//        HttpRequest request = HttpUtil.createPost("http://api.weixin.qq.com/tcb/uploadfile");
//        request.form("cloudPath", cloudPath);
//        request.form("fileContent", file.getInputStream(), file.getOriginalFilename());
//        try (HttpResponse response = request.execute()) {
//            return response.body();
//        }
//    }

    // 微信云托管环境 ID，可根据实际情况修改或从环境变量获取
    private static final String ENVID = "prod-9gof8p3x6a9eb2c8";



    public UploadLinkInfo getUploadLink(String path) {
        String url = "http://api.weixin.qq.com/tcb/uploadfile";
        // 构建请求参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("env", ENVID);
        paramMap.put("path", path);
        String jsonParam = JSONUtil.toJsonStr(paramMap);


        // 创建 HttpClient 实例
        HttpClient httpClient = HttpClients.createDefault();
        // 创建 HttpPost 请求
        HttpPost httpPost = new HttpPost(url);

        try {
            // 设置请求体
            StringEntity entity = new StringEntity(jsonParam, "UTF-8");
            httpPost.setEntity(entity);
            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            // 设置超时时间，这里通过连接管理器来设置，单位为毫秒
            // 注意：这种方式和之前 Hutool 的超时设置略有不同
            // 实际使用中可根据需求调整
            // RequestConfig requestConfig = RequestConfig.custom()
            //        .setConnectTimeout(10000)
            //        .setSocketTimeout(10000)
            //        .build();
            // httpPost.setConfig(requestConfig);

            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);
            // 获取响应实体
            HttpEntity responseEntity = response.getEntity();
            // 获取响应内容
            String responseBody = EntityUtils.toString(responseEntity, "UTF-8");
            System.out.println("获取上传链接：" + responseBody);

            if (JSONUtil.isTypeJSON(responseBody)) {
                // 使用 Hutool 的 JSONUtil 将 JSON 字符串转换为 Java 对象
                UploadLinkInfo uploadLinkInfo = JSONUtil.toBean(responseBody, UploadLinkInfo.class);
                uploadLinkInfo.setKey(path);
                return uploadLinkInfo;
            } else {
                System.out.println("获取的响应不是有效的 JSON 格式：" + responseBody);
                return null;
            }
        } catch (IOException e) {
            System.err.println("请求上传链接时发生 IO 异常：" + e.getMessage());
            return null;
        } finally {
            // 释放连接资源
            httpPost.releaseConnection();
        }
    }


    public DownLoadLinkInfo getDownloadUrls(List<String> fileIds) {
        String url = "https://api.weixin.qq.com/tcb/batchdownloadfile";
        // 构建请求参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("env", ENVID);
        List<Map<String, Object>> fileList = new ArrayList<>();
        for (String fileId : fileIds) {
            Map<String, Object> fileInfo = new HashMap<>();
            fileInfo.put("fileid", fileId);
            fileInfo.put("max_age", 7200);
            fileList.add(fileInfo);
        }
        paramMap.put("file_list", fileList);
        String jsonParam = JSONUtil.toJsonStr(paramMap);
        // 创建 HttpClient 实例
        HttpClient httpClient = HttpClients.createDefault();
        // 创建 HttpPost 请求
        HttpPost httpPost = new HttpPost(url);
        try {
            // 设置请求体
            StringEntity entity = new StringEntity(jsonParam, "UTF-8");
            httpPost.setEntity(entity);
            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);
            // 获取响应实体
            HttpEntity responseEntity = response.getEntity();
            // 获取响应内容
            String responseBody = EntityUtils.toString(responseEntity, "UTF-8");
            System.out.println("获取下载链接：" + responseBody);
            if (JSONUtil.isTypeJSON(responseBody)) {
                // 使用 Hutool 的 JSONUtil 将 JSON 字符串转换为 Java 对象
                return JSONUtil.toBean(responseBody, DownLoadLinkInfo.class);
            } else {
                System.out.println("获取的响应不是有效的 JSON 格式：" + responseBody);
                return null;
            }
        } catch (IOException e) {
            System.err.println("请求下载链接时发生 IO 异常：" + e.getMessage());
            return null;
        } finally {
            // 释放连接资源
            httpPost.releaseConnection();
        }
    }


    public String uploadFile(UploadLinkInfo uploadLinkInfo, MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件为空");
        }
        String url = uploadLinkInfo.getUrl();
        String key = uploadLinkInfo.getKey();
        String signature = uploadLinkInfo.getAuthorization();
        String token = uploadLinkInfo.getToken();
        String cosFileId = uploadLinkInfo.getCosFileId();
        System.out.println("开始上传：" + uploadLinkInfo);
        System.out.println("文件名：" + file.getOriginalFilename());
        // 手动构建 HttpEntity
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("key", key);
        builder.addTextBody("Signature", signature);
        builder.addTextBody("x-cos-security-token", token);
        builder.addTextBody("x-cos-meta-fileid", cosFileId);
        builder.addPart("file", new InputStreamBody(file.getInputStream(), file.getOriginalFilename()));
        HttpEntity entity = builder.build();

        // 创建 HttpClient 实例
        HttpClient httpClient = HttpClients.createDefault();
        // 创建 HttpPost 请求
        HttpPost httpPost = new HttpPost(url);
        // 设置请求实体
        httpPost.setEntity(entity);

        try {
            // 执行请求
            HttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("上传结果：" + statusCode);

            if (statusCode >= 200 && statusCode < 300) {
                // 请求成功，处理响应内容（这里假设不需要处理响应内容，直接返回文件 URL）
                return uploadLinkInfo.getUrl();
            } else {
                // 请求失败，获取响应内容并抛出异常
                String responseBody = EntityUtils.toString(httpResponse.getEntity());
                throw new IOException("文件上传失败，状态码：" + statusCode + "，响应内容：" + responseBody);
            }
        } catch (IOException e) {
            // 处理请求执行过程中的异常
            System.err.println("文件上传时发生 IO 异常：" + e.getMessage());
            throw e;
        } finally {
            // 释放资源
            try {
                httpPost.releaseConnection();
            } catch (Exception ignore) {
                // 忽略释放连接时可能出现的异常
            }
        }
    }
    public String uploadFile1(UploadLinkInfo uploadLinkInfo, MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件为空");
        }
        String url = uploadLinkInfo.getUrl();
        String key = uploadLinkInfo.getKey();
        String signature = uploadLinkInfo.getAuthorization();
        String token = uploadLinkInfo.getToken();
        String cosFileId = uploadLinkInfo.getCosFileId();
        System.out.println("文件名：" + file.getOriginalFilename());

        // 设置字符编码
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.addTextBody("key", key);
        builder.addTextBody("Signature", signature);
        builder.addTextBody("x-cos-security-token", token);
        builder.addTextBody("x-cos-meta-fileid", cosFileId);
        builder.addPart("file", new InputStreamBody(file.getInputStream(), file.getOriginalFilename()));


        HttpEntity entity = builder.build();

        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 手动设置 Content-Type
        String boundary = "Multipart Boundary";
        httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
        httpPost.setEntity(entity);

        try {
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("上传结果：" + statusCode);

            if (statusCode >= 200 && statusCode < 300) {
                return uploadLinkInfo.getUrl();
            } else {
                String responseBody = EntityUtils.toString(response.getEntity());
                throw new IOException("文件上传失败，状态码：" + statusCode + "，响应内容：" + responseBody);
            }
        } catch (IOException e) {
            System.err.println("文件上传时发生 IO 异常：" + e.getMessage());
            throw e;
        } finally {
            httpPost.releaseConnection();
        }
    }

//    public String getUploadFileUrl(String path) throws IOException {
//
////        String cloudPath = "your-cloud-path/" + ;
//        // 使用 try-with-resources 语句确保 HttpResponse 资源被正确关闭
//        HttpRequest request = HttpUtil.createPost("http://api.weixin.qq.com/tcb/uploadfile");
//        request.form("env", "prod-6g2xjx03c54348b1");
//        request.form("path", path);
//        try (HttpResponse response = request.execute()) {
//            System.out.println("获取的JSON 格式：" + response);
//            return response.body();
//        }
//    }
}